package com.roocon.thread.net;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class ServerThread implements Runnable {

  private Socket socket ;
  private InputStream ins;
  private OutputStream out ;

  private PrintWriter pw;

  private static Map<String, String> contentType = new HashMap<>();

  static {
    contentType.put("html", "text/html;charset=utf-8");
    contentType.put("jpg", "image/jpeg");
    contentType.put("ico", "image/x-icon");
  }

  public ServerThread(Socket socket) {
    this.socket = socket;
    init();
  }

  private void  init() {
    try {
      ins = socket.getInputStream();
      out = socket.getOutputStream();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

  @Override public void run() {
    try {
      go();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

  private static final String webRoot = "D:\\opt\\";



  private void go() throws IOException {
    //// 读取内容
    BufferedReader reader = new BufferedReader(new InputStreamReader(ins));
    String line = reader.readLine().split(" ")[1].replace("/","\\");
    if (line.equals("\\")) {
      line += "index.html";
    }
    System.out.println(line);
    String type = contentType.get(line.substring(line.lastIndexOf(".") +1, line.length()));
    System.out.println("type:" + type );

    // 给用户响应
    PrintWriter pw = new PrintWriter(out);
    InputStream i = new FileInputStream(webRoot + line);
    //BufferedReader bf = new BufferedReader(new InputStreamReader(i));
    String c ;
    pw.println("HTTP/1.1 200 OK");

    pw.println("Content-Type:"+type);
    pw.println("Content-Length:" + i.available());
    pw.println("Date:" + new Date());
    //pw.println("Server: Hello");
    pw.println(""); //这个换行很重要
    pw.flush();
    byte[] buff = new byte[1024];
    int len = 0;
    while ((len = i.read(buff)) != -1) {
      //pw.println(c);
      out.write(buff,0,len);
    }
    pw.flush();
    i.close();
    pw.close();
    reader.close();
    socket.close();
  }
}
